//个人信息页
import 'package:dio/dio.dart';
import 'package:enjoy_plus_hm/utils/eventBus.dart';
import 'package:enjoy_plus_hm/utils/request.dart';
import 'package:enjoy_plus_hm/utils/toast.dart';
import 'package:enjoy_plus_hm/utils/token.dart';
// import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
// import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});
  Map userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  //用户信息
  Map userInfo = {};
  //昵称输入框
  final TextEditingController _nikeNameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    setState(() {
      userInfo = widget.userInfo;
      _nikeNameController.text = userInfo['nickName'] ?? '';
    });
  }

  //编辑昵称
  editNickName() async {
    if (_nikeNameController.text.isEmpty) return ToastUtil.showInfo('昵称不能为空!');
    if (_nikeNameController.text.length > 10) {
      return ToastUtil.showInfo('昵称不能大于10个字!');
    }
    try {
      final res = await http.put(
        '/userInfo',
        data: {'nickName': _nikeNameController.text},
      );

      if (res['code'] != 10000) return ToastUtil.showError('更改失败!');
      ToastUtil.showSuccess('更改成功');
      Navigator.pop(context);

      // print(res);
      event.fire(GetUserInfoEvent());
    } catch (e) {
      ToastUtil.showError('网络请求错误!');
    }
  }

  //显示底部半模态   用showModalBottomSheet拉起底部弹窗
  //ListTile列表型组件  可以左侧和右侧都显示数据
  //leading左侧
  //trailing右侧
  showBottomSheet() {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return SizedBox(
          height: 200,
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.camera_alt),
                title: const Text('拍照'),
                trailing: const Icon(Icons.arrow_forward_ios_rounded),
                onTap: () async {
                  final ImagePicker picker = ImagePicker();
                  //拍照
                  final XFile? photo = await picker.pickImage(
                    source: ImageSource.camera,
                  );
                  if (photo != null) {
                    //获取路径(沙箱中的)
                    print(photo.path);
                    uploadAvator(photo.path);
                  }
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo),
                title: const Text('相册'),
                trailing: const Icon(Icons.arrow_forward_ios_rounded),
                onTap: () async {
                  final ImagePicker picker = ImagePicker();
                  //相册
                  final XFile? image = await picker.pickImage(
                    source: ImageSource.gallery,
                  );
                  if (image != null) {
                    //获取路径(沙箱中的)
                    print(image.path);
                    uploadAvator(image.path);
                  }
                },
              ),
            ],
          ),
        );
      },
    );
  }

  //上传图片
  uploadAvator(String imagePath) async {
    print(imagePath);
    try {
      //压缩图片
      // 1. 直接创建临时压缩文件
      // final compressedBytes = await FlutterImageCompress.compressWithFile(
      //   imagePath,
      //   quality: 70, // 70%质量压缩
      //   // minHeight: 800, // 最大高度800px
      //   // minWidth: 800, // 最大宽度800px
      //   autoCorrectionAngle: true,
      // );
      // if (compressedBytes == null) return ToastUtil.showError('图片压缩失败');

      //第一步:创建FormData
      // FormData fd = FormData.fromMap({
      //   'file': kIsWeb //如果是web端单独处理
      //       ? MultipartFile.fromBytes(
      //           await XFile(imagePath).readAsBytes(),
      //           filename: 'avatar.jpg',
      //           contentType: DioMediaType('image', 'jpeg'),
      //         )
      //       //下面是app端可以不做处理
      //       : MultipartFile.fromBytes(compressedBytes, filename: 'avatar.jpg'),
      //   'type': 'avatar',
      // });

      FormData fd = FormData.fromMap({
        //接口需要的数据
        'file': await MultipartFile.fromFile(
          imagePath,
        ), //MultipartFile转换文件,同时是异步的操作
        'type': 'avatar',
      });
      //第二步:发送请求
      final res = await http.post('/upload', data: fd);
      print(res);
      if (res['code'] != 10000) return ToastUtil.showError('上传失败');
      setState(() {
        userInfo['avatar'] = res['data']['url'];
        ToastUtil.showSuccess('上传成功');
      });
    } catch (e) {
      print(e);
      return ToastUtil.showError(e.toString());
    } finally {
      Navigator.pop(context);
    }
  }

  _showDialog() {
    return showDialog(
      context: context,
      builder: (ctx) {
        return AlertDialog(
          title: const Text('温馨提示'),
          content: const Text('确定要退出登录吗？'),
          actions: [
            TextButton(
              child: const Text('取消'),
              onPressed: () {
                Navigator.pop(ctx);
              },
            ),
            TextButton(
              child: const Text('确定'),
              onPressed: () {
                // event.fire(LogoutEvent('退出登录'));
                //清空token
                TokenManager().removeToken();
                //跳转到登录页
                Navigator.pushNamed(context, '/login');
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      //禁用系统级别的返回按钮
      canPop: false,
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: const Text('个人信息'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
          //actions导航栏右侧的widge
          actions: [
            IconButton(
              icon: const Icon(Icons.logout),
              onPressed: () {
                //退出登录
                _showDialog();
                // event.fire(LogoutEvent('退出登录'));
                // TokenManager().removeToken();
                // //跳转到登录页
                // Navigator.pushNamed(context, '/login');
              },
            ),
          ],
          //leading导航栏左侧的widge
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              event.fire(GetUserInfoEvent());
              Navigator.pop(context);
            },
          ),
        ),
        body: ListView(
          padding: const EdgeInsets.all(10),
          children: [
            SizedBox(
              height: 40,
              child: Row(
                children: [
                  const Text('头像', style: TextStyle(fontSize: 16)),
                  const Spacer(),
                  Row(
                    children: [
                      GestureDetector(
                        onTap: () {
                          //头像上传-->相机和相册
                          showBottomSheet();
                        },
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(50.0),
                          child: userInfo['avatar'] != null
                              ? Image.network(
                                  userInfo['avatar'],
                                  width: 40,
                                  height: 40,
                                )
                              : Image.asset(
                                  'assets/images/avatar_1.jpg',
                                  width: 30,
                                  height: 30,
                                ),
                        ),
                      ),
                      const Icon(Icons.arrow_forward_ios, size: 12),
                    ],
                  ),
                ],
              ),
            ),
            Row(
              children: [
                const Text('昵称'),
                const Spacer(),
                Expanded(
                  child: TextField(
                    onEditingComplete: () {
                      //发请求提交数据
                      editNickName();
                    },
                    controller: _nikeNameController,
                    decoration: const InputDecoration(
                      hintText: '请输入昵称',
                      border: InputBorder.none,
                    ),
                    textAlign: TextAlign.right,
                  ),
                ),
                const Icon(Icons.arrow_forward_ios, size: 12),
              ],
            ),
            ElevatedButton(
              onPressed: () {
                editNickName();
              },
              child: const Text('保存'),
            ),
          ],
        ),
      ),
    );
  }
}
